<?php
/**
 * ClassiPress core theme functions
 * This file is the backbone and includes all the core functions
 * Modifying this will void your warranty and could cause
 * problems with your instance of CP. Proceed at your own risk!
 *
 *
 * @version 3.0.2
 * @author David Cowgill
 * @package ClassiPress
 * @copyright 2010 all rights reserved
 *
 */

// current classipress version
$cp_version = '3.0.2';
$cp_edition = 'Personal Edition';

// legacy classipress path variables
$upload_dir = wp_upload_dir();
define('UPLOADS_FOLDER', trailingslashit('classipress'));
define('CP_UPLOAD_DIR', trailingslashit($upload_dir['basedir']) . UPLOADS_FOLDER);

// set global path variables
define('CP_DASHBOARD_URL', get_bloginfo('url').'/dashboard/');
define('CP_PROFILE_URL', get_bloginfo('url').'/profile/');
define('CP_EDIT_URL', get_bloginfo('url').'/edit-item/');
define('CP_ADD_NEW_URL', get_bloginfo('url').'/add-new/');
define('CP_ADD_NEW_CONFIRM_URL', get_bloginfo('url').'/add-new-confirm/');
define('CP_BLOG_URL', cp_detect_blog_path());
define('CP_BLOG_CAT_ID', cp_get_blog_catid());
define('TIMTHUMB', get_bloginfo('template_url').'/includes/timthumb.php');
define('CP_AUTHOR_PATH', get_bloginfo('url').'/author/');
define('FAVICON', get_bloginfo('template_directory').'/images/favicon.ico');
define('CP_POSITION', 3);


// include all the core ClassiPress files
require_once (TEMPLATEPATH . '/includes/theme-enqueue.php');
require_once (TEMPLATEPATH . '/includes/theme-widgets.php');
require_once (TEMPLATEPATH . '/includes/theme-sidebars.php');
require_once (TEMPLATEPATH . '/includes/theme-comments.php');
require_once (TEMPLATEPATH . '/includes/theme-profile.php');
require_once (TEMPLATEPATH . '/includes/theme-security.php');
require_once (TEMPLATEPATH . '/includes/theme-footer.php');
require_once (TEMPLATEPATH . '/includes/theme-header.php');
require_once (TEMPLATEPATH . '/includes/theme-login.php');
require_once (TEMPLATEPATH . '/includes/theme-emails.php');
require_once (TEMPLATEPATH . '/includes/theme-stats.php');
require_once (TEMPLATEPATH . '/includes/admin/admin-options.php');
require_once (TEMPLATEPATH . '/includes/admin/install-script.php');



// display the login message in the header
function cp_login_head() {

    if (is_user_logged_in()) :
        global $current_user;
        get_currentuserinfo();
        ?>
        <?php _e('Welcome,','cp'); ?> <strong><?php echo $current_user->user_login; ?></strong> [ <a href="<?php echo CP_DASHBOARD_URL ?>"><?php _e('My Dashboard','cp'); ?></a> | <a href="<?php echo wp_logout_url(); ?>"><?php _e('Log out','cp'); ?></a> ]&nbsp;
    <?php else : ?>
        <?php _e('Welcome,','cp'); ?> <strong><?php _e('visitor!','cp'); ?></strong> [ <a href="<?php echo get_option('home'); ?>/wp-login.php?action=register"><?php _e('Register','cp'); ?></a> | <a href="<?php echo get_option('home'); ?>/wp-login.php"><?php _e('Login','cp'); ?></a> ]&nbsp;
    <?php endif;

}


// dont show any posts that are sub cats of the blog cat
function cp_post_in_desc_cat($cats, $_post = null) {
    foreach ((array) $cats as $cat) {
        // get_term_children() accepts integer ID only
        $descendants = get_term_children((int) $cat, 'category');
        if ($descendants && in_category($descendants, $_post))
            return true;
    }
    return false;
}

// get the blog category id
function cp_get_blog_catid() {
    $blogcatid = get_option('cp_blog_cat');

    // set to default cat id if option is blank
    if (empty($blogcatid))
        $blogcatid = 1;

    return $blogcatid;
}

// get the blog id and all blog sub cat ids so we can filter them out of ads
function cp_get_blog_cat_ids() {
    $catid = CP_BLOG_CAT_ID;
    $output = array();

    // make sure the blog cat id is set to something
    if(!($catid))
        $catid = 1;

    // put the catid into an array
    $output[] = $catid;

    // get all the sub cats of catid and also put them into the array
    $descendants = get_term_children((int) $catid, 'category');

    foreach($descendants as $key => $value) {
        $output[] = $value;
    }

    // spit out the array and separate each value with a comma
    $allcats = trim(join(',', $output));

    return $allcats;
}

// same function as above but give us the ids in an array. needed on home page for filtering out blog posts
function cp_get_blog_cat_ids_array() {
    $catid = CP_BLOG_CAT_ID;
    $output = array();

    // make sure the blog cat id is set to something
    if(!($catid))
        $catid = 1;

    // put the catid into an array
    $output[] = $catid;

    // get all the sub cats of catid and also put them into the array
    $descendants = get_term_children((int) $catid, 'category');

    foreach($descendants as $key => $value) {
        $output[] = $value;
    }

    return $output;
}

// assemble the blog path
function cp_detect_blog_path() {
    $blogcatid = get_option('cp_blog_cat');

    if (!empty($blogcatid))
        $blogpath = get_category_link(get_option('cp_blog_cat'));
    else // since the cat id field is blank, we need to guess the path
        $blogpath = cp_cat_base().'/blog/';

    return $blogpath;
}

// check to see if it's wp mu
function cp_is_wpmu() {
    if (strpos(get_option('upload_path'), 'blogs.dir') !== false)
        return true;
}

// find out if the category base has been set. If not, use the default of "category"
function cp_cat_base() {
    if ((cp_clean(get_option('category_base')) == ''))
        $cat_base = trailingslashit(get_bloginfo('url')) . 'category';
    else
        $cat_base = trailingslashit(get_bloginfo('url')) . get_option('category_base');

   return $cat_base;
}

// get the date/time ad was posted
function cp_ad_posted($m_time) {
    //$t_time = get_the_time(__('Y/m/d g:i:s A'));
    $time = get_post_time('G', true);
    $time_diff = time() - $time;

    if ( $time_diff > 0 && $time_diff < 24*60*60 )
        $h_time = sprintf( __('%s ago', 'cp'), human_time_diff( $time ) );
    else
        $h_time = mysql2date(get_option('date_format'), $m_time);
    echo $h_time;
}


// display all the custom fields on the single ad page
function cp_get_ad_details($postid, $catid) {
    global $wpdb;
    //$all_custom_fields = get_post_custom($post->ID);
    // see if there's a custom form first based on catid.
    $fid = cp_get_form_id($catid);

    // if there's no form id it must mean the default form is being used
    if(!($fid)) {

        // get all the custom field labels so we can match the field_name up against the post_meta keys
        $sql = $wpdb->prepare("SELECT field_label, field_name "
             . "FROM ". $wpdb->prefix . "cp_ad_fields");

    } else {

        // now we should have the formid so show the form layout based on the category selected
        $sql = $wpdb->prepare("SELECT f.field_label, f.field_name, m.field_pos "
             . "FROM ". $wpdb->prefix . "cp_ad_fields f "
             . "INNER JOIN ". $wpdb->prefix . "cp_ad_meta m "
             . "ON f.field_id = m.field_id "
             . "WHERE m.form_id = '$fid' "
             . "ORDER BY m.field_pos asc");

    }

    $results = $wpdb->get_results($sql);

    if($results) {

        foreach ($results as $result) :
            // now grab all ad fields and print out the field label and value
            $post_meta_val = get_post_meta($postid, $result->field_name, true);

            if (!empty($post_meta_val))
                if($result->field_name != 'cp_price')
                    echo '<li><span>' . $result->field_label . ':</span> ' . cp_make_clickable($post_meta_val) .'</li>'; // make_clickable is a WP function that auto hyperlinks urls

        endforeach;

    } else {

      echo __('No ad details found.', 'cp');

    }
}


// give us the custom form id based on category id passed in
// this is used on the single-default.php page to display the ad fields
function cp_get_form_id($catid) {
    global $wpdb;
    // we first need to see if this ad is using a custom form
    // so lets search for a catid match and return the id if found
    $sql = "SELECT ID, form_cats "
         . "FROM ". $wpdb->prefix . "cp_ad_forms "
         . "WHERE form_status = 'active'";

    $results = $wpdb->get_results($sql);

    if($results) {

        foreach ($results as $result) :

            // put the form_cats into an array
            $catarray = unserialize($result->form_cats);

            // now search the array for the ad catid
            if (in_array($catid, $catarray))
                // when there's a catid match, grab the form id
                $fid = $result->ID;

        endforeach;

        // kick back the form id
        return $fid;

    }

}


// get the first medium image associated to the ad
// used on the home page, search, category, etc
function cp_get_image($post_id = '', $size = 'medium', $num = 1) {
    $images = get_posts(array('post_type' => 'attachment', 'numberposts' => $num, 'post_status' => null, 'post_parent' => $post_id, 'order' => 'ASC', 'orderby' => 'ID'));
    if ($images) {
        foreach ($images as $image) {
            $img_check = wp_get_attachment_image($image->ID, $size, $icon = false);
            $img_check = preg_replace('/title=\"(.*?)\"/','', $img_check);
        }
    } else {
       // show the placeholder image
       if(get_option('cp_ad_images') == 'yes') { $img_check = '<img class="attachment-medium" alt="" title="" src="'. get_bloginfo('template_url') .'/images/no-thumb.jpg" />'; }
    }
    echo $img_check;
}

// get the image associated to the ad used on the single page
function cp_get_image_url($post_id = '', $size = 'medium', $class = '', $num = 1) {
    $images = get_posts(array('post_type' => 'attachment', 'numberposts' => $num, 'post_status' => null, 'post_parent' => $post_id, 'order' => 'ASC', 'orderby' => 'ID'));
    if ($images) {
        foreach ($images as $image) {
              $iarray = wp_get_attachment_image_src($image->ID, $size, $icon = false);
              $img_check = '<img class="'.$class.'" src="'.$iarray[0].'" width="'.$iarray[1].'" height="'.$iarray[2].'" />';
        }
    } else {
        if(get_option('cp_ad_images') == 'yes') {$img_check = '<img class="attachment-medium" alt="" title="" src="'. get_bloginfo('template_url') .'/images/no-thumb.jpg" />'; }
        //cp_single_image_legacy($post_id, get_option('thumbnail_size_w'), get_option('thumbnail_size_h'), 'captify', true);
    }
    echo $img_check;
}


// get the image associated to the ad used on the home page
function cp_get_image_url_feat($post_id = '', $size = 'medium', $class = '', $num = 1) {
    $images = get_posts(array('post_type' => 'attachment', 'numberposts' => $num, 'post_status' => null, 'post_parent' => $post_id, 'order' => 'ASC', 'orderby' => 'ID'));
    if ($images) {
        foreach ($images as $image) {
              $iarray = wp_get_attachment_image_src($image->ID, $size, $icon = false);
              $img_check = '<img class="'.$class.'" src="'.$iarray[0].'" width="'.$iarray[1].'" height="'.$iarray[2].'" alt="" />';
        }
    } else {
        if(get_option('cp_ad_images') == 'yes') { $img_check = '<img class="captify" alt="" title="" src="'. get_bloginfo('template_url') .'/images/no-thumb-sm.jpg" />'; }
        //cp_single_image_legacy($post_id, get_option('thumbnail_size_w'), get_option('thumbnail_size_h'), 'captify', true);
    }
    echo $img_check;
}


// get all the small images for the ad and lightbox href
// important and used on the single page
function cp_get_image_url_single($post_id = '', $size = 'medium', $title = '', $num = 1) {
    $images = get_posts(array('post_type' => 'attachment', 'numberposts' => $num, 'post_status' => null, 'post_parent' => $post_id, 'order' => 'ASC', 'orderby' => 'ID'));
    if ($images) {
        $i=1;
        foreach ($images as $image) {
          $iarray = wp_get_attachment_image_src($image->ID, $size, $icon = false);
          $iarraylg = wp_get_attachment_image_src($image->ID, 'large', $icon = false);
          echo '<a href="'.$iarraylg[0].'" class="ad-gallery" rel="shadowbox[gallery]" title="'.$title.' - '.__('Image ', 'cp').$i.'"><img src="'.$iarray[0].'" alt="image" width="'.$iarray[1].'" height="'.$iarray[2].'" /></a>';
        $i++;
        }
    }
}


// sets the thumbnail pic on the WP admin post
function cp_set_ad_thumbnail($post_id, $thumbnail_id) {
    $thumbnail_html = wp_get_attachment_image($thumbnail_id, 'thumbnail');
    if (!empty($thumbnail_html)) {
        update_post_meta($post_id, '_thumbnail_id', $thumbnail_id);
        die( _wp_post_thumbnail_html($thumbnail_id));
    }
}


// deletes the thumbnail pic on the WP admin post
function cp_delete_ad_thumbnail($post_id) {
    delete_post_meta($post_id, '_thumbnail_id');
    die(_wp_post_thumbnail_html());
}


// gets just the first raw image url
function cp_get_image_url_OLD($postID, $num=1, $order='ASC', $orderby='menu_order', $mime='image') {
    $images = get_posts(array('post_type' => 'attachment','numberposts' => $num,'post_status' => null,'order' => $order,'orderby' => $orderby,'post_mime_type' => $mime,'post_parent' => $postID));
    if ($images) {
        foreach ($images as $image) {
            $single_url = wp_get_attachment_url($image->ID, false);
        }
    }
    echo $single_url;
}


// used for most image resizing for legacy 2.9.x
// soon to be deprecated
function cp_get_single_image($postID, $height=50, $width=50, $num=1, $order='ASC', $orderby='menu_order', $mime='image') {
$attachments = get_posts(array('post_type' => 'attachment','numberposts' => $num,'post_status' => null,'order' => $order,'orderby' => $orderby,'post_mime_type' => $mime,'post_parent' => $postID));
	if ($attachments) {
            foreach ($attachments as $attachment) {
                $single_img = TIMTHUMB.'?src='.wp_get_attachment_url($attachment->ID, false).'&amp;h='.$height.'&amp;w='.$width.'&amp;zc=0"';
            }
	} else {
            $single_img = TIMTHUMB.'?src=/images/no-image.png&amp;h='.$height.'&amp;w='.$width.'&amp;zc=0"';
	}
  echo $single_img;
}



// used for getting the single ad image thumbnails
function cp_get_image_thumbs($postID, $height, $width, $lheight, $lwidth, $num=-1, $order='ASC', $orderby='menu_order', $mime='image') {
    $attachments = get_posts(array('post_type' => 'attachment','numberposts' => $num,'post_status' => null,'order' => $order,'orderby' => $orderby,'post_mime_type' => $mime,'post_parent' => $postID));
    $zc = get_option('cp_tim_thumb_zc'); // get the zoom/crop value
    $i = 1;

    if ($attachments) {
        foreach ($attachments as $attachment) {
            $single_img_thumbs .= '<span id="thumb-wrap"><a rel="group" href="#" title="image '.$i.'" tpath="'.wp_get_attachment_url($attachment->ID, false).'" lpath="'.TIMTHUMB.'?src='.wp_get_attachment_url($attachment->ID, false).'&amp;h='.$lheight.'&amp;w='.$lwidth.'&amp;zc='.$zc.'"><img src="'.TIMTHUMB.'?src='.wp_get_attachment_url($attachment->ID, false).'&amp;h='.$height.'&amp;w='.$width.'&amp;zc='.$zc.'" class="single-thumb" width="'.$width.'" height="'.$height.'" alt="'.get_the_title().' ('.__('image', 'cp').'&nbsp;'.$i.')" title="'.get_the_title().' ('.__('image', 'cp').'&nbsp;'.$i.')" /></a></span>'."\n";
            $i++;
        }
    }
    echo $single_img_thumbs;
}


// legacy function used for ads created with CP 2.9.3 and earlier
// take first image from custom field and return it
function cp_single_image_legacy($postID, $width, $height, $class = 'attachment-medium', $blank = true) {
    $images = get_post_meta($postID, 'images', true); // grab the images from the post custom field
    $zc = get_option('cp_tim_thumb_zc'); // get the zoom/crop value
    $single_img = '';

    if (empty($images)) {
        if ($blank == true) // don't show the placeholder thumbnail if we pass in false
            $single_img = '<img class="'.$class.'" src="'.TIMTHUMB.'?src=/images/no-thumb.jpg&amp;h='.$height.'&amp;w='.$width.'&amp;zc='.$zc.'" border="0" width="'.$width.'" height="'.$height.'" alt="" />';
    } else {
        if (strstr($images, ',')) {
            $matches = explode(',', $images);
            $img_single = $matches[0]; // find the first image
            $single_img = '<img class="'.$class.'" src="'.TIMTHUMB.'?src='.$img_single.'&amp;h='.$height.'&amp;w='.$width.'&amp;zc='.$zc.'" border="0" width="'.$width.'" height="'.$height.'" alt="" />';
        } else {
            if ($blank == true)
                $single_img = '<img class="'.$class.'" src="'.TIMTHUMB.'?src=/images/no-thumb.jpg&amp;h='.$height.'&amp;w='.$width.'&amp;zc='.$zc.'" border="0" width="'.$width.'" height="'.$height.'" alt="" />';
        }
    }
    echo $single_img; //return the results
}


// legacy function used for ads created with CP 2.9.3 and earlier
// takes all images from custom field and returns them on the single ad page
function cp_get_image_thumbs_legacy($postID, $width, $height, $title = '') {
    $images = get_post_meta($postID, 'images', true); //grab the images from the post custom field
    $zc = get_option('cp_tim_thumb_zc'); // get the zoom/crop value
    
    if ($images) {
        $i=1;
        // remove any blank space and trim off the last comma
        $images = explode(',', substr(trim($images),0,-1));
        
        foreach ($images as $image) {
          echo '<a href="'.$image.'" class="ad-gallery" rel="shadowbox[gallery]" title="'.$title.' - '.__('Image ', 'cp').$i.'"><img src="'.TIMTHUMB.'?src='.$image.'&amp;h='.$height.'&amp;w='.$width.'&amp;zc='.$zc.'" alt="" width="'.$width.'" height="'.$height.'" /></a>';
        $i++;
        }
    }
}


// legacy function used on CP 2.9.3 and earlier
// take first image from custom field and use for related ad function
function cp_single_image_raw_legacy($postID, $width, $height) {
    $images = get_post_meta($postID, 'images', true); //grab the images from the post custom field
    $zc = get_option('cp_tim_thumb_zc'); // get the zoom/crop value
    $single_img = '';

    if (empty($images)) {
        $single_img = TIMTHUMB.'?src=/images/no-thumb.jpg&amp;h='.$height.'&amp;w='.$width.'&amp;zc='.$zc.'';
    } else {
        if (strstr($images, ',')) {
            $matches = explode(',', $images);
            $img_single = $matches[0]; // find the first image
            $single_img = trailingslashit(get_bloginfo('url')).trailingslashit(get_option('upload_path')).UPLOADS_FOLDER.$img_single;
        } else {
            $single_img = trailingslashit(get_bloginfo('url')).trailingslashit(get_option('upload_path')).UPLOADS_FOLDER.$images;
        }
        $single_img = TIMTHUMB.'?src='.$single_img.'&amp;h='.$height.'&amp;w='.$width.'&amp;zc='.$zc.'';
    }
    return $single_img; //return the results
}


// get the uploaded file extension and make sure it's an image
function cp_file_is_image($path) {
    $info = @getimagesize($path);
    if (empty($info))
        $result = false;
    elseif (!in_array($info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)))
        $result = false;
    else
        $result = true;

    return apply_filters('cp_file_is_image', $result, $path);
}


// legacy function used on CP 2.9.3 and earlier
// get the ad price and position the currency symbol
function cp_get_price_legacy($postid) {

    if(get_post_meta($postid, 'price', true)) {
        $price_out = get_post_meta($postid, 'price', true);

        // uncomment the line below to change price format
        //$price_out = number_format($price_out, 2, ',', '.');

        if(get_option('cp_curr_symbol_pos') == 'right')
            $price_out = $price_out . get_option('cp_curr_symbol');
        else
            $price_out = get_option('cp_curr_symbol') . $price_out;

    } else {
	
        $price_out = '&nbsp;';
		
    }
	
    echo $price_out;

}


// get the ad price and position the currency symbol
function cp_get_price($postid) {

    if(get_post_meta($postid, 'cp_price', true)) {
        $price_out = get_post_meta($postid, 'cp_price', true);

        // uncomment the line below to change price format
        //$price_out = number_format($price_out, 2, '.', ',');

        $price_out = cp_pos_currency($price_out);

    } else {
	
        $price_out = '&nbsp;';
		
    }
	
    echo $price_out;
}


// pass in the price and get the position of the currency symbol
function cp_pos_price($numout) {

    $numout = cp_pos_currency($numout);
	
    echo $numout;

}

// figure out the position of the currency symbol and return it with the price
function cp_pos_currency($price_out) {

	if (get_option('cp_curr_symbol_pos') == 'left')
		$price_out = get_option('cp_curr_symbol') . $price_out;
	elseif (get_option('cp_curr_symbol_pos') == 'left_space')
		$price_out = get_option('cp_curr_symbol') . '&nbsp;' . $price_out;
	elseif (get_option('cp_curr_symbol_pos') == 'right')
		$price_out = $price_out . get_option('cp_curr_symbol');
	else
		$price_out = $price_out . '&nbsp;' . get_option('cp_curr_symbol');
	
	return $price_out;
	
}


// on ad submission form, check images for valid file size and type
function cp_validate_image() {
    $error_msg  = array();
    $max_size = (get_option('cp_max_image_size') * 1024); // 1024 K = 1 MB. convert into bytes so we can compare file size to max size. 1048576 bytes = 1MB.

    while(list($key,$value) = each($_FILES['image']['name'])) {
        $value = strtolower($value); // added for 3.0.1 to force image names to lowercase. some systems throw an error otherwise
        if(!empty($value)) {
            if ($max_size < $_FILES['image']['size'][$key]) {
                $size_diff = number_format(($_FILES['image']['size'][$key] - $max_size)/1024);
                $max_size_fmt = number_format(get_option('cp_max_image_size'));
                $error_msg[] = '<strong>'.$_FILES['image']['name'][$key].'</strong> '. sprintf( __('exceeds the %s KB limit by %s KB. Please go back and upload a smaller image.', 'cp'), $max_size_fmt, $size_diff );
            }
            elseif (!cp_file_is_image($_FILES['image']['tmp_name'][$key])) {
                $error_msg[] = '<strong>'.$_FILES['image']['name'][$key].'</strong> '. __('is not a valid image type (.gif, .jpg, .png). Please go back and upload a different image.', 'cp');
            }
        }
    }
    return $error_msg;
}


// process each image that's being uploaded
function cp_process_new_image() {
    global $wpdb;
    $postvals = '';

    for($i=0; $i < count($_FILES['image']['tmp_name']);$i++) {
        if (!empty($_FILES['image']['tmp_name'][$i])) {
            // rename the image to a random number to prevent junk image names from coming in
            $renamed = mt_rand(1000,1000000).".".cp_find_ext($_FILES['image']['name'][$i]);

            //Hack since WP can't handle multiple uploads as of 2.8.5
            $upload = array( 'name' => $renamed,'type' => $_FILES['image']['type'][$i],'tmp_name' => $_FILES['image']['tmp_name'][$i],'error' => $_FILES['image']['error'][$i],'size' => $_FILES['image']['size'][$i] );

            // need to set this in order to send to WP media
            $overrides = array('test_form' => false);

            // check and make sure the image has a valid extension and then upload it
            $file = cp_image_upload($upload);

            if ($file) // put all these keys into an array and session so we can associate the image to the post after generating the post id
                $postvals['attachment'][$i] = array( 'post_title' => $renamed,'post_content' => '','post_excerpt' => '','post_mime_type' => $file['type'],'guid' => $file['url'], 'file' => $file['file'] );
        }
    }
    return $postvals;
}


// this ties the uploaded files to the correct ad post and creates the multiple image sizes.
function cp_associate_images($post_id,$file) {
    for($i=0; $i < count($file);$i++) {
        $attachment = array( 'post_title' => $file[$i]['post_title'],'post_content' => $file[$i]['post_content'],'post_excerpt' => $file[$i]['post_excerpt'],'post_mime_type' => $file[$i]['post_mime_type'],'guid' => $file[$i]['guid'] );
        $attach_id = wp_insert_attachment($attachment, $file[$i]['file'], $post_id);

        // create multiple sizes of the uploaded image via WP controls
        wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $file[$i]['file']));

        // this only does a specific resize.
        // image_make_intermediate_size($file, $width, $height, $crop=false)
        // $crop Optional, default is false. Whether to crop image to specified height and width or resize.
        //wp_update_attachment_metadata($attach_id, image_make_intermediate_size($file[$i]['file'], 50, 50, true));
        //wp_update_attachment_metadata($attach_id, image_make_intermediate_size($file[$i]['file'], 25, 25, true));
    }
}


// get all the images associated to the ad and display the
// thumbnail with checkboxes for deleting them
// used on the ad edit page
function cp_get_ad_images($ad_id) {
    $args = array('post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $ad_id, 'order' => 'ASC', 'orderby' => 'ID');

    // get all the images associated to this ad
    $images = get_posts($args);

    // print_r($images); // for debugging

    // get the total number of images already on this ad
    // we need it to figure out how many upload fields to show
    $imagecount = count($images);

    // make sure we have images associated to the ad
    if ($images) :

        $i = 1;
        foreach ($images as $image) :   
        ?>
        
        <li>
            <label><?php _e('Image', 'cp'); ?> <?php echo $i ?>:</label>

            <div id="thumb-container">
                <span id="thumb-wrap-edit">
                    <?php echo wp_get_attachment_link($image->ID); ?>
                    <input class="checkbox" type="checkbox" name="image[]" value="<?php echo $image->ID; ?>">
                </span>
            </div>

            <div class="clr"></div>
        </li>

        <?php
        $i++;
        endforeach;

    endif;

    // returns a count of array keys so we know how many images currently
    // are being used with this ad. this value is needed for cp_ad_edit_image_input_fields()
    return $imagecount;
}


// gives us a count of how many images are associated to an ad
function cp_count_ad_images($ad_id) {
    $args = array('post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $ad_id, 'order' => 'ASC', 'orderby' => 'ID');

    // get all the images associated to this ad
    $images = get_posts($args);

    // get the total number of images already on this ad
    // we need it to figure out how many upload fields to show
    $imagecount = count($images);

    // returns a count of array keys so we know how many images currently
    // are being used with this ad.
    return $imagecount;
}


// calculates total number of image input upload boxes
// minus the number of existing images
function cp_ad_edit_image_input_fields($imagecount) {

    // get the max number of images allowed option
    $maximages = get_option('cp_num_images');

    // figure out how many image upload fields we need
    $imageboxes = ($maximages - $imagecount);

    // now loop through and print out the upload fields
    for($i=0; $i < $imageboxes;$i++) :
    ?>
        <li>
            <label><?php _e('Add Image','cp') ?>:</label>
            <input type="file" name="image[]" class="fileupload">
            <div class="clr"></div>
        </li>
    <?php
    endfor;
    ?>

    <p class="small"><?php printf(__('You are allowed %s image(s) per ad.','cp'), $maximages) ?> <?php echo get_option('cp_max_image_size') ?><?php _e('KB max file size per image.','cp') ?> <?php _e('Check the box next to each image you wish to delete.','cp') ?></p>
    <div class="clr"></div>

<?php
}


// make sure it's an image file and then upload it
function cp_image_upload($upload) {
    if (cp_file_is_image($upload['tmp_name'])) {
        $overrides = array('test_form' => false);
        // move image to the WP defined upload directory and set correct permissions
        $file = wp_handle_upload($upload, $overrides);
    }
    return $file;
}


// delete the image from WordPress
function cp_delete_image() {
    foreach( (array) $_POST['image'] as $img_id_del ) {
        $img_del = & get_post($img_id_del);

        if ( $img_del->post_type == 'attachment' )
            if ( !wp_delete_attachment($img_id_del, true) )
                wp_die( __('Error in deleting the image.', 'cp') );
    }
}


// checks if a user is logged in, if not redirect them to the login page
function auth_redirect_login() {
    $user = wp_get_current_user();
    if ( $user->id == 0 ) {
        nocache_headers();
        wp_redirect(get_option('siteurl') . '/wp-login.php?redirect_to=' . urlencode($_SERVER['REQUEST_URI']));
        exit();
    }
}


// gets the ad tags
function cp_get_the_term_list( $id = 0, $taxonomy, $before = '', $sep = '', $after = '' ) {
    $terms = get_the_terms( $id, $taxonomy );

    if (is_wp_error($terms))
        return $terms;

    if (empty($terms))
        return false;

    foreach ($terms as $term) {
        $link = get_term_link($term, $taxonomy);
        if (is_wp_error($link))
            return $link;
        $term_links[] = $term->name . ', ';
    }

    $term_links = apply_filters( "term_links-$taxonomy", $term_links );

    return $before . join( $sep, $term_links ) . $after;
}


// change ad to draft if it's expired
function cp_has_ad_expired($post_id) {
    global $wpdb;

    // check to see if ad is legacy or not
    if(get_post_meta($post_id, 'expires', true))
        $expire_date = get_post_meta($post_id, 'expires', true);
    else
        $expire_date = get_post_meta($post_id, 'cp_sys_expire_date', true);

    // debugging variables
    // echo date_i18n('m/d/Y H:i:s') . ' <-- current date/time GMT<br/>';
    // echo $expire_date . ' <-- expires date/time<br/>';

    // if current date is past the expires date, change post status to draft
    if (strtotime(date('Y-m-d H:i:s')) > (strtotime($expire_date))) :
        $my_post = array();
        $my_post['ID'] = $post_id;
        $my_post['post_status'] = 'draft';
        wp_update_post($my_post);

        return true;
    endif;
}


/**
 *
 * ClassiPress helper functions
 *
 */


// checks whether string begins with given string.
// i.e. if (string_starts_with($host, 'http://localhost/')) { //do stuff }
function cp_str_starts_with($string, $search) {
    return (strncmp($string, $search, strlen($search)) == 0);
}

// strip out everything except for numbers
function cp_numbers_only($string) {
    $string = preg_replace('[^0-9]', '', $string);
    return $string;
}

// strip out everything except for numbers
function cp_letters_only($string) {
    $string = preg_replace('/[^a-z]/i', '', $string);
    return $string;
}

// strip out everything except numbers and letters
function cp_numbers_letters_only($string) {
    $string = preg_replace('/[^a-z0-9]/i', '', $string);
    return $string;
}

// for the price field to make only numbers, periods, and commas
function cp_clean_price($string) {
    $string = preg_replace('/[^0-9.,]/', '', $string);
    return $string;
}

// for the price field to make only numbers, periods, and commas
function cp_clean_tags($string) {
    $string = preg_replace('/\s*,\s*/', ',', rtrim(trim($string), ' ,'));
    return $string;
}

// pass strings in to clean
function cp_clean($string) {
    $string = stripslashes($string);
    $string = trim($string);
    return $string;
}

// strip tags and limit characters to 5,000
function cp_filter($text) {
    $text = strip_tags($text);
    $text = trim($text);
    $char_limit = 5000;
    if( strlen($text) > $char_limit ) {
        $text = substr($text, 0, $char_limit);
    }
    return $text;
}


//This function separates the extension from the rest of the file name and returns it
function cp_find_ext ($filename) {
    $filename = strtolower($filename);
    $exts = split("[/\\.]", $filename);
    $n = count($exts)-1;
    $exts = $exts[$n];
    return $exts;
}

// error message output function
function cp_error_msg($error_msg) {
    $msg_string = '';
    foreach ($error_msg as $value) {
        if(!empty($value)) {
            $msg_string = $msg_string . '<div class="error">' . $msg_string = $value.'</div><div class="pad5"></div>';
        }
    }
    return $msg_string;
}

// replace all \n with just <br />
function cp_nl2br($text) {
   return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />'));
}

// End Classipress helper functions



// tinyMCE text editor
function cp_tinymce($width=540, $height=400) {
?>
<script type="text/javascript">
    <!--
    tinyMCE.init({
        mode : "exact",
        theme : "advanced",
        skin : "default",
        elements : "description",
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,cleanup,code,|,forecolor,backcolor",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,
        theme_advanced_resize_horizontal : false,
        content_css : "<?php echo get_bloginfo('template_directory'); ?>/styles/master.css",
        languages : 'en',
        disk_cache : true,
        width : "<?php echo $width; ?>",
        height : "<?php echo $height; ?>",
        // update validation status on change hack to work with jquery validation
        onchange_callback: function(editor) {
          tinyMCE.triggerSave();
          $("#" + editor.id).valid();
        }
    });
    -->
</script>

<?php
}

// get the visitor IP so we can include it with the ad submission
function cp_getIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {  //check ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  //to check ip is pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}


// 336 x 280 ad box on single page
function cp_single_ad_336x280 () { 

        if (get_option('cp_adcode_336x280') <> '') {

            echo stripslashes(get_option('cp_adcode_336x280'));

        } else {

            if (get_option('cp_adcode_336x280_url') || !get_option('cp_adcode_336x280_dest')) {
            ?>

                <a href="<?php echo get_option('cp_adcode_336x280_dest') ?>" target="_blank"><img src="<?php echo get_option('cp_adcode_336x280_url') ?>" alt="" border="0" /></a>

        <?php
            }
        }

}


// saves the ad on the tpl-edit-item.php page template
function cp_update_listing() {
    global $wpdb;

    // check to see if html is allowed
    if (get_option('cp_allow_html') != 'yes')
        $post_content = cp_filter($_POST['post_content']);
    else
        $post_content = $_POST['post_content'];

    // keep only numeric, commas or decimal values
    if (!empty($_POST['cp_price']))
        $_POST['cp_price'] = cp_clean_price($_POST['cp_price']);

    // keep only values and insert/strip commas if needed and put into an array
    if (!empty($_POST['tags_input']))
        $_POST['tags_input'] = cp_clean_tags($_POST['tags_input']);
        $new_tags = explode(',', $_POST['tags_input']);


    // put all the ad elements into an array
    // these are the minimum required fields for WP (except tags)
    $update_ad                      = array();
    $update_ad['ID']                = trim($_POST['ad_id']);
    $update_ad['post_title']        = cp_filter($_POST['post_title']);
    $update_ad['post_content']      = trim($post_content);
    $update_ad['tags_input']        = $new_tags; // array
    //$update_ad['post_category']   = array((int)cp_filter($_POST['cat'])); // maybe use later if we decide to let users change categories

    //print_r($update_ad).' <- new ad array<br>'; // for debugging

    // update the ad and return the ad id
    $post_id = wp_update_post($update_ad);


    if($post_id) {

        // now update all the custom fields
        foreach($_POST as $meta_key => $meta_value) {
            if (cp_str_starts_with($meta_key, 'cp_'))
                //echo $meta_key . ' <--metakey <br/>' . $meta_value . ' <--metavalue<br/><br/>'; // for debugging
                update_post_meta($post_id, $meta_key, $meta_value);
        }

        $errmsg = '<div class="box-yellow"><b>' . __('Your ad has been successfully updated.','cp') . '</b> <a href="' . CP_DASHBOARD_URL . '">' . __('Return to my dashboard','cp') . '</a></div>';

    } else {
        // the ad wasn't updated so throw an error
        $errmsg = '<div class="box-red"><b>' . __('There was an error trying to update your ad.','cp') . '</b></div>';

    }

    return $errmsg;

}


// builds the edit ad form on the tpl-edit-item.php page template
function cp_edit_ad_formbuilder($results, $getad) {
    global $wpdb;

    foreach ($results as $result) :

        // get all the custom fields on the post and put into an array
        $custom_field_keys = get_post_custom_keys($getad->ID);

        if(!$custom_field_keys) continue;
            // wp_die('Error: There are no custom fields');

        // we only want key values that match the field_name in the custom field table or core WP fields.
        if (in_array($result->field_name, $custom_field_keys) || ($result->field_name == 'post_content') || ($result->field_name == 'post_title') || ($result->field_name == 'tags_input')) :

            // we found a match so go fetch the custom field value
            $post_meta_val = get_post_meta($getad->ID, $result->field_name, true);

            // now loop through the form builder and make the proper field and display the value
            switch($result->field_type) {

            case 'text box':
            ?>
                <li>
                    <label><?php echo $result->field_label;?>: <?php if($result->field_req) echo '<span class="colour">*</span>' ?></label>
                    <input name="<?php echo $result->field_name; ?>" type="text" class="text<?php if ($result->field_req) echo ' required'; ?>" style="min-width:200px;" value="<?php if ($result->field_name == 'post_title') {echo $getad->post_title;} elseif ($result->field_name == 'tags_input') { echo rtrim(trim(cp_get_the_term_list($getad->ID,'post_tag')), ',');} else { echo $post_meta_val; } ?>" />
                    <div class="clr"></div>
                </li>
            <?php
            break;

            case 'drop-down':
            ?>
                <li>
                    <label><?php echo $result->field_label;?>: <?php if($result->field_req) echo '<span class="colour">*</span>' ?></label>
                    <select name="<?php echo $result->field_name; ?>" class="dropdownlist<?php if ($result->field_req) echo ' required'; ?>">

                    <?php
                    $options = explode(',', $result->field_values);

                    foreach ($options as $option)
                    {
                        ?>

                            <option style="min-width:177px" <?php if ($post_meta_val == $option) { echo 'selected="selected"';} ?> value="<?php echo $option; ?>"><?php echo $option; ?></option>

                        <?php
                    }
                    ?>

                    </select>
                    <div class="clr"></div>
                </li>

            <?php
            break;

            case 'text area':

            ?>
                <li>
                    <label><?php echo $result->field_label;?>: <?php if($result->field_req) echo '<span class="colour">*</span>' ?></label>
                    <div class="clr"></div>
                    <textarea rows="4" cols="23" name="<?php echo $result->field_name; ?>" id="<?php if ($result->field_name == 'post_content') { echo 'description'; } else { echo $result->field_name; } ?>"><?php if ($result->field_name == 'post_content') { echo $getad->post_content; } else { echo $post_meta_val; } ?></textarea>
                    <div class="clr"></div>
                </li>
            <?php
            break;

            }

        endif;

    endforeach;

}

// shows how much time is left before the ad expires
function cp_timeleft($theTime) {
    $now = strtotime("now");
    $timeLeft = $theTime - $now;

    $days_label = __('days','cp');
    $day_label = __('day','cp');
    $hours_label = __('hours','cp');
    $hour_label = __('hour','cp');
    $mins_label = __('mins','cp');
    $min_label = __('min','cp');
    $secs_label = __('secs','cp');
    $r_label = __('remaining','cp');
    $expired_label = __('This ad has expired','cp');

    if($timeLeft > 0)
    {
    $days = floor($timeLeft/60/60/24);
    $hours = $timeLeft/60/60%24;
    $mins = $timeLeft/60%60;
    $secs = $timeLeft%60;

    if($days == 01) {$d_label=$day_label;} else {$d_label=$days_label;}
    if($hours == 01) {$h_label=$hour_label;} else {$h_label=$hours_label;}
    if($mins == 01) {$m_label=$min_label;} else {$m_label=$mins_label;}

    if($days){$theText = $days . " " . $d_label;
    if($hours){$theText .= ", " .$hours . " " . $h_label;}}
    elseif($hours){$theText = $hours . " " . $h_label;
    if($mins){$theText .= ", " .$mins . " " . $m_label;}}
    elseif($mins){$theText = $mins . " " . $m_label;
    if($secs){$theText .= ", " .$secs . " " . $secs_label;}}
    elseif($secs){$theText = $secs . " " . $secs_label;}}
    else{$theText = $expired_label;}
    return $theText;
}


// Breadcrumb for the top of pages
function cp_breadcrumb() {
 
  $delimiter = '&raquo;';
  $currentBefore = '<span class="current">';
  $currentAfter = '</span>';

  if ( !is_home() || !is_front_page() || is_paged() ) {

    echo '<div id="crumbs">';

    global $post;
    $home = get_bloginfo('url');
    echo '<a href="' . $home . '">' . __('Home', 'cp') . '</a> ' . $delimiter . ' ';

    if ( is_category() ) {
      global $wp_query;
      $cat_obj = $wp_query->get_queried_object();
      $thisCat = $cat_obj->term_id;
      $thisCat = get_category($thisCat);
      $parentCat = get_category($thisCat->parent);
      if ($thisCat->parent != 0) echo(get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' '));
      echo $currentBefore;
      single_cat_title();
      echo $currentAfter;

    } elseif ( is_day() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo '<a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
      echo $currentBefore . get_the_time('d') . $currentAfter;

    } elseif ( is_month() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo $currentBefore . get_the_time('F') . $currentAfter;

    } elseif ( is_year() ) {
      echo $currentBefore . get_the_time('Y') . $currentAfter;

    } elseif ( is_single() ) {
      $cat = get_the_category(); $cat = $cat[0];
      echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
      echo $currentBefore;
      the_title();
      echo $currentAfter;

    } elseif ( is_page() && !$post->post_parent ) {
      echo $currentBefore;
      the_title();
      echo $currentAfter;

    } elseif ( is_page() && $post->post_parent ) {
      $parent_id  = $post->post_parent;
      $breadcrumbs = array();
      while ($parent_id) {
        $page = get_page($parent_id);
        $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
        $parent_id  = $page->post_parent;
      }
      $breadcrumbs = array_reverse($breadcrumbs);
      foreach ($breadcrumbs as $crumb) echo $crumb . ' ' . $delimiter . ' ';
      echo $currentBefore;
      the_title();
      echo $currentAfter;

    } elseif ( is_search() ) {
      echo $currentBefore . __('Search results for', 'cp') .' &#39;' . get_search_query() . '&#39;' . $currentAfter;

    } elseif ( is_tag() ) {
      echo $currentBefore . 'Posts tagged &#39;';
      single_tag_title();
      echo '&#39;' . $currentAfter;

    } elseif ( is_author() ) {
       global $author;
      $userdata = get_userdata($author);
      echo $currentBefore . __('Articles posted by', 'cp') .'&nbsp;' . $userdata->display_name . $currentAfter;

    } elseif ( is_404() ) {
      echo $currentBefore . __('Error 404', 'cp') . $currentAfter;
    }

    if ( get_query_var('paged') ) {
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
      echo __('Page', 'cp') . ' ' . get_query_var('paged');
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
    }

    echo '</div>';

  }

}


// custom related posts function based on tags
// not being used in 3.0 yet
function cp_related_posts($postID, $width, $height) {
    global $wpdb, $post;
    $output = '';

    if (!get_option('cp_similar_items')) {

// if (!$post_id) { $post_id = $post->ID; }

        $q = "SELECT DISTINCT object_id, post_title, post_content ".
                "FROM $wpdb->term_relationships r, $wpdb->term_taxonomy t, $wpdb->posts p ".
                "WHERE t.term_id IN (".
                "SELECT t.term_id FROM $wpdb->term_relationships r, $wpdb->term_taxonomy t ".
                "WHERE r.term_taxonomy_id = t.term_taxonomy_id ".
                "AND t.taxonomy = 'category' ".
                "AND r.object_id = $postID".
                ") ".
                "AND r.term_taxonomy_id = t.term_taxonomy_id ".
                "AND p.post_status = 'publish' ".
                "AND p.ID = r.object_id ".
                "AND object_id <> $postID ".
                "AND p.post_type = 'post' ".
                "ORDER BY RAND() LIMIT 5";

        $entries = $wpdb->get_results($q);

//$output .= '<h3>'. __('Similar Items','cp') . '</h3>';
        $output .= '<div id="similar-items">';

        if ($entries) {

            $output .= '<ul>';

            foreach ($entries as $post) {
                $output .= '<li class="clearfix">';
                $output .= '<div class="list_ad_img"><img src="'.cp_single_image_raw($post->object_id, $width, $height).'" /></div>';
                $output .= '<span class="list_ad_wrap_wide"><a class="list_ad_link_wide" href="'.get_permalink($post->object_id).'">'. $post->post_title. '</a><br/>';
                $output .= substr(strip_tags($post->post_content), 0, 165).'...</span>';
                $output .= '</li>';
            }

        } else {
            $output .= '<p>' . __('No matches found', 'cp') . '</p>';
        }
        $output .= '</ul>';
        $output .= '</div>';

        return $output;
    }
}

// 468 x 60 ad box in header
function cp_header_ad_468x60 () {

    if (get_option('cp_adcode_468x60') <> '') {

        echo stripslashes(get_option('cp_adcode_468x60'));

    } else {

        if (!get_option('cp_adcode_468x60_url') || !get_option('cp_adcode_468x60_dest')) {
        ?>

            <a href="#"><img class="" src="<?php echo bloginfo("template_directory") ?>/images/468x60-banner.jpg" border="0" width="468" height="60" alt="" /></a>

       <?php } else { ?>

            <a href="<?php echo get_option('cp_adcode_468x60_dest') ?>" target="_blank"><img src="<?php echo get_option('cp_adcode_468x60_url') ?>" border="0" /></a>
        <?php
        }
    }
}



// show category with price dropdown
function cp_dropdown_categories_prices( $args = '' ) {
    $defaults = array( 'show_option_all' => '', 'show_option_none' => '','orderby' => 'ID', 'order' => 'ASC','show_last_update' => 0, 'show_count' => 0,'hide_empty' => 1, 'child_of' => 0,'exclude' => '', 'echo' => 1,'selected' => 0, 'hierarchical' => 0,'name' => 'cat', 'class' => 'postform','depth' => 0, 'tab_index' => 0 );
    
    $defaults['selected'] = ( is_category() ) ? get_query_var( 'cat' ) : 0;
    $r = wp_parse_args( $args, $defaults );
    $r['include_last_update_time'] = $r['show_last_update'];
    extract( $r );

    $tab_index_attribute = '';
    if ( (int) $tab_index > 0 )
        $tab_index_attribute = " tabindex=\"$tab_index\"";
    $categories = get_categories( $r );
    $output = '';
    if ( ! empty( $categories ) ) {
        $output = "<select name='$name' id='$name' class='$class' $tab_index_attribute>\n";

        if ( $show_option_all ) {
            $show_option_all = apply_filters( 'list_cats', $show_option_all );
            $selected = ( '0' === strval($r['selected']) ) ? " selected='selected'" : '';
            $output .= "\t<option value='0'$selected>$show_option_all</option>\n";
        }

        if ( $show_option_none ) {
            $show_option_none = apply_filters( 'list_cats', $show_option_none );
            $selected = ( '-1' === strval($r['selected']) ) ? " selected='selected'" : '';
            $output .= "\t<option value='-1'$selected>$show_option_none</option>\n";
        }

        if ( $hierarchical )
            $depth = $r['depth'];  // Walk the full depth.
        else
            $depth = -1; // Flat.

        $output .= cp_category_dropdown_tree( $categories, $depth, $r );
        $output .= "</select>\n";
    }

    $output = apply_filters( 'wp_dropdown_cats', $output );

    if ( $echo )
        echo $output;

    return $output;
}

// needed for the cp_dropdown_categories_prices function
function cp_category_dropdown_tree() {
    $args = func_get_args();
    if ( empty($args[2]['walker']) || !is_a($args[2]['walker'], 'Walker') )
        $walker = new cp_CategoryDropdown;
    else
        $walker = $args[2]['walker'];
    return call_user_func_array(array( &$walker, 'walk' ), $args );
}

// needed for the cp_category_dropdown_tree function
class cp_CategoryDropdown extends Walker {
    var $tree_type = 'category';
    var $db_fields = array ('parent' => 'parent', 'id' => 'term_id');
    function start_el(&$output, $category, $depth, $args) {
        $pad = str_repeat('&nbsp;', $depth * 3);
        $cat_name = apply_filters('list_cats', $category->name, $category);
        $output .= "\t<option class=\"level-$depth\" value=\"".$category->term_id."\">";
        $output .= $pad.$cat_name;
        $output .= ' - ' . get_option('cp_curr_symbol') . get_option('cp_cat_price_'.$category->cat_ID) . '</option>'."\n";;
    }
}


// slimmed down non-plugin version of WP-PageNavi (2.50) by Lester 'GaMerZ' Chan http://lesterchan.net
function cp_pagination($before = '', $after = '') {
    global $wpdb, $wp_query;
    if (!is_single()) {

        $pagenavi_options = array(
                'pages_text' => __('Page %CURRENT_PAGE% of %TOTAL_PAGES%','cp'),
                'current_text' => '%PAGE_NUMBER%',
                'page_text' => '%PAGE_NUMBER%',
                'first_text' => __('&lsaquo;&lsaquo; First','cp'),
                'last_text' => __('Last &rsaquo;&rsaquo;','cp'),
                'next_text' => __('&rsaquo;&rsaquo;','cp'),
                'prev_text' => __('&lsaquo;&lsaquo;','cp'),
                'dotright_text' => '',
                'dotleft_text' => '',
                'style' => 1,
                'num_pages' => 15,
                'always_show' => 0,
                'num_larger_page_numbers' => 3,
                'larger_page_numbers_multiple' => 10,
        );

        $posts_per_page = intval(get_query_var('posts_per_page'));
        $paged = intval(get_query_var('paged'));
        $numposts = $wp_query->found_posts;
        $max_page = $wp_query->max_num_pages;
        if(empty($paged) || $paged == 0) {
            $paged = 1;
        }
        $pages_to_show = intval($pagenavi_options['num_pages']);
        $larger_page_to_show = intval($pagenavi_options['num_larger_page_numbers']);
        $larger_page_multiple = intval($pagenavi_options['larger_page_numbers_multiple']);
        $pages_to_show_minus_1 = $pages_to_show - 1;
        $half_page_start = floor($pages_to_show_minus_1/2);
        $half_page_end = ceil($pages_to_show_minus_1/2);
        $start_page = $paged - $half_page_start;
        if($start_page <= 0) {
            $start_page = 1;
        }
        $end_page = $paged + $half_page_end;
        if(($end_page - $start_page) != $pages_to_show_minus_1) {
            $end_page = $start_page + $pages_to_show_minus_1;
        }
        if($end_page > $max_page) {
            $start_page = $max_page - $pages_to_show_minus_1;
            $end_page = $max_page;
        }
        if($start_page <= 0) {
            $start_page = 1;
        }
        $larger_per_page = $larger_page_to_show*$larger_page_multiple;
        $larger_start_page_start = (cp_round($start_page, 10) + $larger_page_multiple) - $larger_per_page;
        $larger_start_page_end = cp_round($start_page, 10) + $larger_page_multiple;
        $larger_end_page_start = cp_round($end_page, 10) + $larger_page_multiple;
        $larger_end_page_end = cp_round($end_page, 10) + ($larger_per_page);
        if($larger_start_page_end - $larger_page_multiple == $start_page) {
            $larger_start_page_start = $larger_start_page_start - $larger_page_multiple;
            $larger_start_page_end = $larger_start_page_end - $larger_page_multiple;
        }
        if($larger_start_page_start <= 0) {
            $larger_start_page_start = $larger_page_multiple;
        }
        if($larger_start_page_end > $max_page) {
            $larger_start_page_end = $max_page;
        }
        if($larger_end_page_end > $max_page) {
            $larger_end_page_end = $max_page;
        }
        if($max_page > 1 || intval($pagenavi_options['always_show']) == 1) {
            $pages_text = str_replace("%CURRENT_PAGE%", number_format_i18n($paged), $pagenavi_options['pages_text']);
            $pages_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $pages_text);
            echo $before.'<div class="whiteblock">'."\n";
                if(!empty($pages_text)) {
                    echo '<div class="pages"><span>'.$pages_text.'</span>';
                }
                if ($start_page >= 2 && $pages_to_show < $max_page) {
                    $first_page_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $pagenavi_options['first_text']);
                    echo '<a href="'.clean_url(get_pagenum_link()).'" class="first" title="'.$first_page_text.'">'.$first_page_text.'</a>';
                    if(!empty($pagenavi_options['dotleft_text'])) {
                        echo '<span class="extend">'.$pagenavi_options['dotleft_text'].'</span>';
                    }
                }
                if($larger_page_to_show > 0 && $larger_start_page_start > 0 && $larger_start_page_end <= $max_page) {
                    for($i = $larger_start_page_start; $i < $larger_start_page_end; $i+=$larger_page_multiple) {
                        $page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $pagenavi_options['page_text']);
                        echo '<a href="'.clean_url(get_pagenum_link($i)).'" class="page" title="'.$page_text.'">'.$page_text.'</a>';
                    }
                }
                previous_posts_link($pagenavi_options['prev_text']);
                for($i = $start_page; $i  <= $end_page; $i++) {
                    if($i == $paged) {
                        $current_page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $pagenavi_options['current_text']);
                        echo '<span class="current">'.$current_page_text.'</span>';
                    } else {
                        $page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $pagenavi_options['page_text']);
                        echo '<a href="'.clean_url(get_pagenum_link($i)).'" class="page" title="'.$page_text.'">'.$page_text.'</a>';
                    }
                }
                next_posts_link($pagenavi_options['next_text'], $max_page);
                if($larger_page_to_show > 0 && $larger_end_page_start < $max_page) {
                    for($i = $larger_end_page_start; $i <= $larger_end_page_end; $i+=$larger_page_multiple) {
                        $page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $pagenavi_options['page_text']);
                        echo '<a href="'.clean_url(get_pagenum_link($i)).'" class="page" title="'.$page_text.'">'.$page_text.'</a>';
                    }
                }
                if ($end_page < $max_page) {
                    if(!empty($pagenavi_options['dotright_text'])) {
                        echo '<span class="extend">'.$pagenavi_options['dotright_text'].'</span>';
                    }
                    $last_page_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $pagenavi_options['last_text']);
                    echo '<a href="'.clean_url(get_pagenum_link($max_page)).'" class="last" title="'.$last_page_text.'">'.$last_page_text.'</a>';
                }

            echo '</div><div class="clr"></div></div>'.$after."\n";
        }
    }
}

// category menu drop-down display
function cp_cat_menu_drop_down($cols = 3, $subs = 0) {


    // get all cats except for the blog. have to use exclude_tree instead of the documented exclude param
    $cats = get_categories('hide_empty=0&hierarchical=0&pad_counts=1&show_count=1&orderby=name&order=ASC&exclude_tree='.CP_BLOG_CAT_ID);

    // remove all sub cats from the array
    foreach ($cats as $key => $value){
        if ($value->category_parent != 0)
            unset($cats[$key]);
    }

    $i = 0;
    $cat_cols = $cols; // change this to add/remove columns
    $total_main_cats = count($cats); // total number of parent cats
    $cats_per_col = round($total_main_cats / $cat_cols); // items per column

    // loop through all the sub
    foreach($cats as $cat) {

        if (($i == 0) || ($i == $cats_per_col) || ($i == ($cats_per_col * 2))) {
        ?>

            <div class="catcol<?php if ($i == 0) echo ' first'; ?>">

        <?php
        }
        ?>

        <ul>
            <li class="maincat"><a href="<?php echo get_category_link($cat->term_id); ?>"><?php echo $cat->name; ?></a> (<?php echo $cat->category_count; ?>)</li>

        <?php
        // don't show any sub cats
        if($subs <> 999) :

            // now get all the sub cats based off the parent cat id
            $subcats = wp_list_categories('orderby=name&order=asc&show_count=1&hierarchical=0&use_desc_for_title=0&hide_empty=0&depth=1&title_li=&echo=0&number='.$subs.'&child_of='.$cat->cat_ID);

            // strip out the default wp title tag since the use_desc_for_title param doesn't seem to work in WP 2.9.2
            $subcats = preg_replace('/title=\"(.*?)\"/','',$subcats);

            // if you want to strip out the no categories text, just uncomment the line below
            // $subcats = str_replace('<li>No categories</li>', '', $subcats);

            // print out all the subcats for the current parent cat
            echo $subcats;

        endif;
        ?>

        </ul>


        <?php

        if (($i == ($cats_per_col - 1)) || ($i == (($cats_per_col * 2) - 1)) || ($i == ($total_main_cats - 1))) {
        ?>

            </div><!-- /catcol -->

        <?php
        }

        $i++;
    }
}



// directory home page category display
function cp_directory_cat_columns($cols) {

    // get all cats except for the blog
    $cats = get_categories('hide_empty=0&hierarchical=0&pad_counts=1&show_count=1&orderby=name&order=ASC&exclude='.CP_BLOG_CAT_ID);

    // remove all sub cats from the array
    foreach ($cats as $key => $value){
        if ($value->category_parent != 0)
            unset($cats[$key]);
    }

    $i = 0;
    $cat_cols = $cols; // change this to add/remove columns
    $total_main_cats = count($cats); // total number of parent cats
    $cats_per_col = round($total_main_cats / $cat_cols); // items per column

    // loop through all the sub
    foreach($cats as $cat) {

        if (($i == 0) || ($i == $cats_per_col) || ($i == ($cats_per_col * 2))) {
        ?>

            <div class="catcol">

        <?php
        }
        ?>

        <ul>
            <li class="maincat"><a href="<?php echo get_category_link($cat->term_id); ?>"><?php echo $cat->name; ?></a> (<?php echo $cat->category_count; ?>)</li>

        <?php
        // now get all the sub cats based off the parent cat id
        $subcats = wp_list_categories('orderby=name&order=asc&hierarchical=0&show_count=1&use_desc_for_title=0&hide_empty=0&depth=1&number='.get_option('cp_dir_sub_num').'&title_li=&echo=0&child_of='.$cat->cat_ID);

        // strip out the default wp title tag since the use_desc_for_title param doesn't seem to work in WP 2.9.2
        $subcats = preg_replace('/title=\"(.*?)\"/','',$subcats);

        // if you want to strip out the no categories text, just uncomment the line below
        // $subcats = str_replace('<li>No categories</li>', '', $subcats);

        // print out all the subcats for the current parent cat
        echo $subcats;
        ?>

        </ul>

        <?php

        if (($i == ($cats_per_col - 1)) || ($i == (($cats_per_col * 2) - 1)) || ($i == ($total_main_cats - 1))) {
        ?>
            </div><!-- /catcol -->

        <?php
        }

        $i++;
    }

}


// Round To The nearest value used in cp_pagination
function cp_round($num, $tonearest) {
   return floor($num/$tonearest)*$tonearest;
}


// If you want to automatically resize youtube videos uncomment the filter
function cp_resize_youtube($content) {
    return str_replace('width="640" height="385"></embed>', 'width="480" height="295"></embed>', $content);
}
//add_filter('the_content', 'cp_resize_youtube', 999);


/**
 * Custom ClassiPress search engine to search
 * and include custom fields
 * @global <type> $wpdb
 * @param <type> $join
 * @return <type>
 *
 *
 */


// search only ads and not pages
function cp_is_type_page() {
    global $post;
    if ($post->post_type == 'page')
        return true;
    else
        return false;
}

// get all custom field names so we can use them for search
function cp_custom_search_fields() {
    global $wpdb;

    $sql = "SELECT field_name "
            . "FROM ". $wpdb->prefix . "cp_ad_fields p "
            . "WHERE p.field_name LIKE 'cp_%' ";

    $results = $wpdb->get_results($sql);

    if($results) {
        foreach ($results as $result) :
            // put the fields into an array
            $custom_fields[] = $result->field_name;
        endforeach;
    }

    return $custom_fields;
}

// search on custom fields
function custom_search_join($join) {
    if ( is_search() && isset($_GET['s'])) {
        global $wpdb;
       $join = " LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id ";
    }
    return($join);
}

// search on custom fields
function custom_search_groupby($groupby) {
    if ( is_search() && isset($_GET['s'])) {
        global $wpdb;
        $groupby = " $wpdb->posts.ID ";
    }
    return($groupby);
}

// search on custom fields
function custom_search_where($where) {
    global $wpdb;
    $old_where = $where;
    if (is_search() && isset($_GET['s'])) {

        // get the custom fields to add to search
        $custom_fields = cp_custom_search_fields();
        // enter additional legacy custom fields here
        $custom_fields_more = array('name', 'price', 'phone', 'location');
        // now merge the two arrays together
        $customs = array_merge($custom_fields,$custom_fields_more);

        $query = '';
        $var_q = stripslashes($_GET['s']);
        if ($_GET['sentence']) {
            $search_terms = array($var_q);
        }
        else {
            preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $var_q, $matches);
            $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
        }
        $n = ($_GET['exact']) ? '' : '%';
        $searchand = '';
        foreach((array)$search_terms as $term) {
            $term = addslashes_gpc($term);
            $query .= "{$searchand}(";
            $query .= "($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
            $query .= " OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}')";
            foreach($customs as $custom) {
                $query .= " OR (";
                $query .= "($wpdb->postmeta.meta_key = '$custom')";
                $query .= " AND ($wpdb->postmeta.meta_value  LIKE '{$n}{$term}{$n}')";
                $query .= ")";
            }
            $query .= ")";
            $searchand = ' AND ';
        }
        $term = $wpdb->escape($var_q);
        if (!$_GET['sentense'] && Count($search_terms) > 1 && $search_terms[0] != $var_q) {
            $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
            $search .= " OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}')";
        }

        if (!empty($query)) {
            $where = " AND ({$query}) AND ($wpdb->posts.post_status = 'publish') ";
        }
    }
    return($where);
}


// ClassiPress RSS blog feed for the dashboard page
function cp_dashboard_classipress() {
global $cp_rss_feed;
	wp_widget_rss_output($cp_rss_feed, array('items' => 10, 'show_author' => 0, 'show_date' => 1, 'show_summary' => 1));
}

// ClassiPress RSS twitter feed for the dashboard page
function cp_dashboard_twitter() {
global $cp_twitter_rss_feed;
	wp_widget_rss_output($cp_twitter_rss_feed, array('items' => 5, 'show_author' => 0, 'show_date' => 1, 'show_summary' => 0));
}

// ClassiPress RSS forum feed for the dashboard page
function cp_dashboard_forum() {
global $cp_forum_rss_feed;
	wp_widget_rss_output($cp_forum_rss_feed, array('items' => 5, 'show_author' => 0, 'show_date' => 1, 'show_summary' => 1));
}

// helper function used by cp_make_clickable to make email string a link
function cp_make_email_clickable($matches) {
    $email = $matches[2] . '@' . $matches[3];
    return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
}

// helper function used by cp_make_clickable to make http string a link
function cp_make_url_clickable($matches) {
    $url = $matches[2];

    $url = esc_url($url);
    if ( empty($url) )
            return $matches[0];

    return $matches[1] . "<a target=\"_blank\" href=\"$url\" rel=\"nofollow\">$url</a>";
}

// looks for any http or email address and automatically hyperlinks it
function cp_make_clickable($ret) {
    $ret = ' ' . $ret;
    // in testing, using arrays here was found to be faster
    $ret = preg_replace_callback('#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/=?@\[\](+-]|[.,;:](?![\s<]|(\))?([\s]|$))|(?(1)\)(?![\s<.,;:]|$)|\)))+)#is', 'cp_make_url_clickable', $ret);
    $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', 'cp_make_email_clickable', $ret);
    // this one is not in an array because we need it to run last, for cleanup of accidental links within links
    $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
    $ret = trim($ret);
    return $ret;
}


// if an ad is created and doesn't have an expiration date,
// make sure to insert one based on the Ad Listing Period option.
// all ads need an expiration date otherwise they will automatically
// expire. this is common when customers manually create an ad through
// the WP admin new post or when using an automated scrapper script
function cp_check_expire_date($post_id) {
    global $wpdb;

    // we don't want to add the expires date to blog posts
    if (in_category(CP_BLOG_CAT_ID) || cp_post_in_desc_cat(CP_BLOG_CAT_ID) )  {

        // do nothing

    } else {

        // add default expiration date if the expired custom field is blank or empty
        if (!get_post_meta($post_id, 'cp_sys_expire_date', true) || (get_post_meta($post_id, 'cp_sys_expire_date', true) == '')) :
            $ad_length = get_option('cp_prun_period');
            if(!$ad_length) $ad_length = '365'; // if the prune days is empty, set it to one year
            $ad_expire_date = date_i18n('m/d/Y H:i:s', strtotime('+' . $ad_length . ' days')); // don't localize the word 'days'
            add_post_meta($post_id, 'cp_sys_expire_date', $ad_expire_date, true);
        endif;

    }

}

// runs when a post is published, or is edited and status is "published"
add_filter('publish_post', 'cp_check_expire_date', 9, 3);



// search on custom fields
add_filter('posts_join', 'custom_search_join');
add_filter('posts_where', 'custom_search_where');
add_filter('posts_groupby', 'custom_search_groupby');

// set the current params of ClassiPress
$cp_rss_feed = 'http://feeds2.feedburner.com/classipress';
$cp_twitter_rss_feed = 'http://twitter.com/statuses/user_timeline/classipress.rss';
$cp_forum_rss_feed = 'http://wpclassipress.com/forum/rss.php';
$cp_db_tables = array('cp_ad_forms', 'cp_ad_meta', 'cp_ad_fields', 'cp_ad_pop_daily', 'cp_ad_pop_total' , 'cp_ad_packs', 'cp_order_info');


// activate support for .mo localization files
load_theme_textdomain('cp');

// activate support for thumbnails
if (function_exists('add_theme_support')) { // added in 2.9
    add_theme_support('post-thumbnails', array('post', 'page'));
    set_post_thumbnail_size(100, 100); // normal post thumbnails
    //add_image_size('blog-thumbnail', 400, 9999); // permalink thumbnail size
    add_image_size('blog-thumbnail', 150, 150); // blog post thumbnail size, box resize mode
    add_image_size('sidebar-thumbnail', 50, 50); // sidebar blog thumbnail size, box resize mode
}

?>